using B.S.Medical.Api.Read.Application.Command.Home;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Medical;
using B.S.Medical.Domain.Payment;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Home
{
    public class GetHomeStatisticsHandler : IRequestHandler<GetHomeStatisticsCommand, ApiResult<HomeStatisticsDto>>
    {
        private readonly IBaseRepository<RegisterModel> _registerRepo;
        private readonly IBaseRepository<PatientModel> _patientRepo;
        private readonly IBaseRepository<PaymentRecordModel> _paymentRepo;

        public GetHomeStatisticsHandler(
            IBaseRepository<RegisterModel> registerRepo,
            IBaseRepository<PatientModel> patientRepo,
            IBaseRepository<PaymentRecordModel> paymentRepo)
        {
            _registerRepo = registerRepo;
            _patientRepo = patientRepo;
            _paymentRepo = paymentRepo;
        }

        public async Task<ApiResult<HomeStatisticsDto>> Handle(GetHomeStatisticsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<HomeStatisticsDto>();
            try
            {
                var today = DateTime.Today;
                var tomorrow = today.AddDays(1);

                // 今日预约人数（今日创建的挂号记录）
                var todayAppointments = _registerRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.CreateTime >= today && x.CreateTime < tomorrow)
                    .Count();

                // 今日到诊人数（状态为已就诊的挂号记录）
                var todayVisits = _registerRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.VisitDate >= today && x.VisitDate < tomorrow && x.Status == "已就诊")
                    .Count();

                // 今日门诊收入（今日已支付的挂号费用）
                var todayOutpatientRevenue = _registerRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.VisitDate >= today && x.VisitDate < tomorrow && x.Status == "已就诊")
                    .Sum(x => x.Fee);

                // 今日充值金额（今日的支付记录）
                var todayRechargeAmount = _paymentRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.CreateTime >= today && x.CreateTime < tomorrow && x.IsPaid)
                    .Sum(x => x.Amount);

                // 新增患者人数（今日创建的患者）
                var newPatients = _patientRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.CreateTime >= today && x.CreateTime < tomorrow)
                    .Count();

                // 今日挂号数（今日的挂号记录总数）
                var todayRegistrations = _registerRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.CreateTime >= today && x.CreateTime < tomorrow)
                    .Count();

                var statistics = new HomeStatisticsDto
                {
                    TodayAppointments = todayAppointments,
                    TodayVisits = todayVisits,
                    TodayOutpatientRevenue = todayOutpatientRevenue,
                    TodayRechargeAmount = todayRechargeAmount,
                    NewPatients = newPatients,
                    TodayRegistrations = todayRegistrations
                };

                res.Data = statistics;
                res.Msg = "获取首页统计数据成功!";
                res.Code = ApiEnum.Success;
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Msg = "获取首页统计数据异常：" + ex.Message;
                res.Code = ApiEnum.Error;
            }
            return await Task.FromResult(res);
        }
    }
} 